package com.ydlclass.compress.impl;

import com.ydlclass.compress.AbstractCompress;
import com.ydlclass.exceptions.CompressException;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Gzip压缩方式
 * @Author duWenJian
 * @Date 2024/2/25 11:49
 * @Version 1.0
 */
@Slf4j
public class GzipCompress extends AbstractCompress {
    @Override
    public byte[] compress(byte[] bytes) {
        if (bytes == null){
            return null;
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
              GZIPOutputStream gzip = new GZIPOutputStream(baos);){
            gzip.write(bytes);
            gzip.finish();
            byte[] compressBody = baos.toByteArray();
            log.debug("对字节数据进行压缩，长度由原来的:{}压缩至:{}",bytes.length,compressBody.length);
            return compressBody;
        } catch (IOException e) {
            log.error("gzip压缩失败原因是:{}",e);
            throw new CompressException(e);
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        if (bytes == null){
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             GZIPInputStream gzipInputStream = new GZIPInputStream(bais);)
        {
            byte[] DecompressBody = gzipInputStream.readAllBytes();
            log.debug("对字节数据进行解压缩，长度由原来的:{}解压至:{}",bytes.length,DecompressBody.length);
            return DecompressBody;
        } catch (IOException e) {
            log.error("解压缩出现异常:{}",e);
            throw new CompressException(e);

        }
    }
}
